<template>
  <div id="container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button
        >
      </el-col>
    </el-row>

    <el-table
      :data="methodList"
      border
      style="width: 100%"
    >
      <!--      <el-table-column-->
      <!--        prop="id"-->
      <!--        label="ID"-->
      <!--        align="center"-->
      <!--        width="180">-->
      <!--      </el-table-column>-->
      <el-table-column
        prop="name"
        label="方法名称"
        align="center"
        width="180"
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="方法类型"
      >
        <template slot-scope="scope">
          {{ getMethodName(scope.row.mainType) }}
        </template>

      </el-table-column>
      <el-table-column
        prop="executeMain"
        align="center"
        label="方法配置"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="method.title" :visible.sync="method.open"  width="800px" append-to-body>

      <el-form :model="funcForm" class="funcClass addDialog" :rules="funcRules" ref="funcDialog" label-width="100px">
        <el-form-item label="方法名称" class="funcName" prop="name">
          <el-input v-model="funcForm.name" placeholder="请输入方法名称"></el-input>
        </el-form-item>

        <el-form-item label="方法类型" class="funcType" prop="mainType">
          <el-select v-model="funcForm.mainType" placeholder="请选择方法类型" @change="changeFuncType">
            <el-option
              v-for="(item, index) in methodTypeData"
              :key="index"
              :label="item.name"
              :value="item.value"
              :disabled="edit"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!--   js文件上传     -->
        <el-form-item label="js文件上传" v-if="funcForm.mainType == '2'" prop="jsFilesUpload">
<!--          <imageUpload @input="getJsFilesUpload" :limit="1" :value="jsFilesPath" :fileType="fileType" />-->

          <FileUpload :fileType="fileType" :limit="1" @input="getJsFilesUpload" :value="jsFilesPath" :isShowCopy="true" />
        </el-form-item>

        <!--  富文本框  -->
        <el-form-item  class="jsExcuteClass" label="方法配置" prop="executeMain">
          <div class="myCodeMirror">
            <component v-bind:is="currentComponent"
                       v-if="codeMirror"
                       @input="getMyCode"
                       ref="codeMirror"
                       :value="formatCode(funcForm.executeMain)">
            </component>

          </div>
        </el-form-item>

<!--        <el-form-item v-if="funcForm.mainType == '1'"  class="jsExcuteClass" label="方法配置" prop="executeMain">-->
<!--          <div class="myCodeMirror">-->
<!--            <JavaMyCodeMirror-->
<!--              v-if="codeMirror"-->
<!--              @input="getMyCode"-->
<!--              ref="codeMirror"-->
<!--              :value="formatCode(funcForm.executeMain)"-->
<!--            />-->
<!--          </div>-->
<!--        </el-form-item>-->

<!--        <el-form-item v-if="funcForm.mainType == '2'"  class="jsExcuteClass" label="方法配置" prop="executeMain">-->
<!--          <div class="myCodeMirror">-->
<!--            <JavaScriptMyCodeMirror-->
<!--              v-if="codeMirror"-->
<!--              @input="getMyCode"-->
<!--              ref="codeMirror"-->
<!--              :value="formatCode(funcForm.executeMain)"-->
<!--            />-->

<!--          </div>-->
<!--        </el-form-item>-->

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFuncForm()">确 定</el-button>
        <el-button @click="method.open = false">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  addSupplierMain,
  updateSupplierMain,
  getSupplierMain,
  listSupplierMain,
  delSupplierMain
} from '@/api/pm/supplierMain';
// import {addSupplierMainImport} from "@/api/pm/supplierMainImport";
import MyCodeMirror from '@/components/CodeMirror/index.vue';

import JavaMyCodeMirror from '@/components/CodeMirror/indexJava';
import JavaScriptMyCodeMirror from "@/components/CodeMirror/indexJavaScript";

//使用js-beautify格式化js代码
import { js_beautify } from 'js-beautify';

import FileUpload from "@/components/FileUpload";

export default {
  name: 'Method',
  components: {MyCodeMirror, JavaMyCodeMirror, JavaScriptMyCodeMirror, FileUpload },
  props: {
    "supplierId": String
  },
  // created() {
  //   console.log('method的created方法');
  //
  //   this.getList();
  // },
  data() {
    return {
      methodList: [],
      methodTypeData: [
        {name: 'java方法', value: '1'},
        {name: 'js方法', value: '2'}
      ],
      method: {
        title: '新增方法',
        open: false
      },
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      funcForm: {
        name: '',
        mainType: '1',
        executeMain: ''
      },
      //方法字段的验证
      funcRules: {
        name: [
          {required: true, message: '方法名称不能为空', trigger: 'blur'}
        ],
        mainType: [
          {required: true, message: '方法类型不能为空', trigger: 'blur'}
        ],
        executeMain: [
          {required: true, message: '方法配置不能为空', trigger: 'blur'}
        ]
      },
      edit: false,
      //js编辑器里面的代码
      myCode: '',
      codeMirror: true,
      jsFilesPath: '',
      fileType: ['js'],
      componentList: [
        {value: 1, name: 'JavaMyCodeMirror'},
        {value: 2, name: 'JavaScriptMyCodeMirror'},
      ]
    }
  },
  computed: {
    getMethodName() {
      return function (value) {
        let methodObj = this.methodTypeData.find(method => method.value == value);
        return methodObj.name;
      }
    },
    currentComponent() {
      return this.componentList.find(item=>item.value == this.funcForm.mainType)?.name || '';
    }
  },
  watch: {
    'supplierId': {
      handler(val) {
        this.getList();
      },
      immediate: true
    }
  },
  methods: {
    messageMethods(msg, type) {
      this.$message({
        message: msg,
        type: type
      });
    },

    getList() {
      let param = {
        "supplierId": this.supplierId,
        "pageNum": this.queryParams.pageNum,
        "pageSize": this.queryParams.pageSize
      };

      listSupplierMain(param).then(res => {
        if (res.code == 200) {
          this.methodList = res.rows;
          this.total = res.total;
        }
      }).catch(error => {
        // console.log(error);
      });
    },
    //新增方法
    handleAdd() {
      this.funcForm.supplierId = this.supplierId;

      this.funcForm.name        = '';
      this.funcForm.mainType    = '1';
      this.funcForm.executeMain = '';

      this.edit = false;
      this.method.open = true;
    },
    //提交方法
    // 方法配置提交
    submitFuncForm() {
      this.$refs['funcDialog'].validate((valid) => {
        if (valid) {
          this.saveFunc();
        }
      })
    },

    //java方法和js方法
    //mainType=1， java方法；mainType=2, js方法。
    saveFunc() {
      if (!this.edit) { //新增
        addSupplierMain(this.funcForm).then((res) => {
          let type = res.code == 200 ? 'success' : 'error';
          this.messageMethods(res.msg, type);
          this.method.open = false;
          this.getList();
        }).catch((error) => {
          this.messageMethods(error, 'error');
          this.method.open = false;
          this.getList();
        });
      } else { //编辑
        updateSupplierMain(this.funcForm).then(res => {
          let type = res.code == 200 ? 'success' : 'error';
          this.messageMethods(res.msg, type);
          this.method.open = false;
          this.getList();
        }).catch(error => {
          this.messageMethods(error, 'error');
          this.method.open = false;
          this.getList();
        });
      }
    },


    // 删除方法
    handleDelete(row) {
      this.$modal.confirm('确定删除该方法吗?')
        .then(() => {
          return delSupplierMain(row.id);
        })
        .then(res => {
          let type = res.code == 200 ? 'success' : 'error';
          this.messageMethods(res.msg, type);
          this.getList();
        }).catch(() => {
      });
    },

    //修改方法
    handleUpdate(row) {
      let id = row.id;

      this.funcForm = Object.assign({}, row);
      this.funcForm.supplierId = this.supplierId;

      getSupplierMain(id).then(res => {
        if (res.code == 200) {
          let data = res.data;
          this.funcForm = Object.assign({}, data);
        }
      }).catch(error => {
        // console.log(error);
      });

      this.edit = true;
      this.method.title = '修改方法';
      this.method.open = true;

      this.codeMirror = false;
      this.$nextTick(()=>{
        this.codeMirror = true;
      });
    },

    //方法类型改变
    changeFuncType() {
      this.funcForm.executeMain = '';
    },

    //获取编写的js代码
    getMyCode(value) {
      if(value) {
        this.myCode = value;
        this.funcForm.executeMain = value.replace(/\n|\r|\r\n|\t/g,"");
      }
    },

    // 格式化js代码
    formatCode(code) {
      return code && this.edit ?  js_beautify(code) : '';
    },

    // js文件上传
    getJsFilesUpload(value) {

    }
  }
}
</script>

<style lang="scss" scoped>

.jsExcuteClass {
  //display: flex;
  //justify-content: flex-start;

  //::v-deep .el-form-item__label {
  //  width: 80px !important;
  //}
}
.myCodeMirror {
  width: 500px;
}
.filedClass {
  width: 100px;
}

.funcName {
  ::v-deep .el-input--medium {
    width: 500px !important;
  }
}

.funcType {
  ::v-deep .el-input--medium {
    width: 500px !important;
  }
}

</style>
